package com.sky.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sky.annotation.AutoFill;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.entity.Employee;
import com.sky.enumeration.OperationType;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.service.EmployeeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        // 1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        // 2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            // 账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        // 将密码加密为MD5
        password = DigestUtils.md5DigestAsHex(password.getBytes());

        // 密码比对：用数据库中的密码与刚刚加密的密码进行判断
        if (!password.equals(employee.getPassword())) {
            // 密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            // 账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        // 3、返回实体对象
        return employee;
    }

    @Override
    public Boolean add(EmployeeDTO employeeDTO) {
        Employee data = new Employee();

        // 将employee的属性拷贝到data中
        BeanUtils.copyProperties(employeeDTO, data);

        // 设置密码，默认密码123456
        data.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));

        // 用户状态：1正常 0禁用
        data.setStatus(StatusConstant.ENABLE);

        // 设置当前记录的创建时间和修改时间
        data.setCreateTime(LocalDateTime.now());
        data.setUpdateTime(LocalDateTime.now());

        // 从当前线程中取出用户ID
        Long currentId = BaseContext.getCurrentId();

        // 设置当前记录创建人id和修改人id
        data.setCreateUser(currentId);
        data.setUpdateUser(currentId);

        // 新增员工
        return employeeMapper.insert(data) == 1;
    }

    @Override
    public Page<Employee> page(EmployeePageQueryDTO employeePageQueryDTO) {
        QueryWrapper<Employee> queryWrapper = new QueryWrapper<>();

        if (StringUtils.hasText(employeePageQueryDTO.getName())) {
            queryWrapper.like("name", "%" + employeePageQueryDTO.getName() + "%");
            System.out.println(employeePageQueryDTO);
        }

        int num = employeePageQueryDTO.getPage(); // 当前页
        int size = employeePageQueryDTO.getPageSize(); // 每页数量

        Page<Employee> page = new Page<>(num, size);
        employeeMapper.selectPage(page, queryWrapper);

        return page;
    }

    @Override
    public Boolean status(Integer status, Integer id) {
        Employee employee = employeeMapper.selectById(id);
        employee.setStatus(status);

        return employeeMapper.updateById(employee) == 1;
    }
}
